package org.dc.activity.workDay;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.dc.R;
import org.dc.entity.Shift;
import org.dc.entity.Visit;
import org.dc.entity.WorkDay;
import org.dc.service.PersistenceManager;
import org.dc.utlity.UIUtility;
import org.dc.view.FreeTimeView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @user: Vladimir Chernishov
 * @date: 2/28/12
 * @time: 5:55 PM
 */
public class WorkDayScr extends Activity {

    private final static DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    private Map<Integer,Shift> shifts;
    private List<WorkDay> workDays;
    private Calendar currentDate;
    private int currentDay;
    private Date today;
    private FreeTimeView freeTime;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewGroup layout = (ViewGroup) getLayoutInflater().inflate(R.layout.work_day, null);
        setContentView(layout);
        TableLayout table = (TableLayout )findViewById(R.id.workDayHeaderTable);

        UIUtility.updateTableWidth(table, getWindowManager().getDefaultDisplay().getWidth());

        LinearLayout freeTimeLayout = (LinearLayout) findViewById(R.id.workDayFreeTimeLayout);
        freeTime = new FreeTimeView(this);
        freeTimeLayout.addView(freeTime);

        loadWeekData(Calendar.getInstance());
        initWeekDaysButtons();
        refreshWeekDaysButtons();
    }

    private void loadWeekData(Calendar calendar) {
        this.shifts = PersistenceManager.getShiftDao(this).getShiftsMap();

        this.currentDate = calendar;
        this.currentDay = this.currentDate.get(Calendar.DAY_OF_WEEK);
        if(this.currentDay == Calendar.SUNDAY){
            this.currentDay = 6;
        } else {
            this.currentDay -=2;
        }

        this.workDays = PersistenceManager.getWorkDayDao(this).getWorkDaysForWeek((Calendar) this.currentDate.clone());
        this.today = this.workDays.get(this.currentDay).getDate();
    }

    private void refreshWeekDaysButtons() {
        TableRow buttons = (TableRow)findViewById(R.id.workDayButtonsRow);
        for(int i = 0; i < buttons.getChildCount(); i++){
            Button button = (Button) buttons.getChildAt(i);
            if(currentDay == i){
                button.setEnabled(false);
                button.setBackgroundResource(R.color.activeButton);
            } else {
                button.setEnabled(true);
                button.setBackgroundResource(R.color.WHITE);
            }
        }
    }

    private void initWeekDaysButtons() {
        TableRow buttons = (TableRow)findViewById(R.id.workDayButtonsRow);
        for(int i = 0; i < buttons.getChildCount(); i++){
            Button button = (Button) buttons.getChildAt(i);
            final int current = i;
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    currentDay = current;
                    refreshOnHeaderButtonClick();
                    Log.d("WORKDAY.DAYBUTTONS", "Clicked " + current);
                }
            });
        }
    }

    private void refreshOnHeaderButtonClick() {
        refreshWeekDaysButtons();
        refreshVisitsTable();
    }


    @Override
    protected void onResume() {
        super.onResume();
        initHeaderTable();
        refreshWeekDaysButtons();
        refreshVisitsTable();
    }

    private void refreshVisitsTable() {
        TableLayout workDayTime = (TableLayout)findViewById(R.id.workDayTime);
        workDayTime.removeAllViews();
        List<Visit> visits = PersistenceManager.getVisitDao(this).getVisistsForDay(workDays.get(currentDay).getDate());
        for (Visit visit : visits) {
            TableRow row = new TableRow(this);
            workDayTime.addView(row);

            addCell(String.valueOf(visit.getVisitId()), row);
            addCell(visit.getDate().toString(), row);
            addCell(String.valueOf(visit.getTime()/60) + ":" + String.valueOf(visit.getTime()%60), row);
            addCell(String.valueOf(visit.getLength()), row);
            addCell(visit.getDescription(), row);
            addCell(visit.getCreated().toString(), row);
        }
        UIUtility.updateTableWidth(workDayTime, getWindowManager().getDefaultDisplay().getWidth());
        
        WorkDay workDay = workDays.get(currentDay);
        Shift shift = shifts.get(workDay.getShiftId());
        
        updateFreeTimeTable(shift, workDay, visits);

        freeTime.refresh(shift, workDay, visits);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                freeTime.invalidate();
            }
        });
    }

    private void updateFreeTimeTable(Shift shift, WorkDay workDay, List<Visit> visits) {
        TableLayout mainTable = (TableLayout) findViewById(R.id.workDayFreeTimeTable);
        mainTable.removeAllViews();

        if(shift == null){
            return;
        }

        int workHours = shift.getTill() - shift.getFrom();
        int cells = workHours + 2;
        
        TableRow row = new TableRow(this);
        mainTable.addView(row);
        
        for(int i = 0; i < cells; i++){
            LinearLayout cell = new LinearLayout(this);
            cell.setBackgroundResource(R.color.WHITE);
            TableRow.LayoutParams layout = new TableRow.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layout.setMargins(1, 1, 1, 1);
            cell.setLayoutParams(layout);
            cell.setOrientation(LinearLayout.VERTICAL);

            final int hours = createFreeTimeCell(shift, visits, workHours, i, cell);

            cell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(WorkDayScr.this, NewVisitScr.class);
                    Calendar calendar = (Calendar) workDays.get(currentDay).getCalendar().clone();
                    calendar.set(Calendar.HOUR_OF_DAY, hours);
                    calendar.set(Calendar.MINUTE, 0);
                    i.putExtra("Calendar", calendar);
                    startActivity(i);
                }
            });

            row.addView(cell);
        }

        UIUtility.updateTableWidth(mainTable, getWindowManager().getDefaultDisplay().getWidth());
    }

    private int createFreeTimeCell(Shift shift, List<Visit> visits, int workHours, int i, LinearLayout cell) {
        int hours;
        if( i == 0){
            TextView text = new TextView(this);
            text.setText("Before");
            cell.addView(text);
            hours = shift.getFrom() -1;
            for (Visit visit : visits) {
                if(visit.getTime()/60 < shift.getFrom()){
                    createVisitCell(cell, visit);
                }
            }
        }else if( i > 0 && i <= workHours ){
            TextView hoursText = new TextView(this);
            hours = shift.getFrom() + i - 1;
            hoursText.setText(String.valueOf(hours) +":00");
            cell.addView(hoursText);
            for (Visit visit : visits) {
                if(visit.getTime()/60 == hours){
                    createVisitCell(cell, visit);
                }
            }
        }else {
            TextView text = new TextView(this);
            text.setText("After");
            cell.addView(text);
            hours = shift.getTill();
            for (Visit visit : visits) {
                if(visit.getTime()/60 > shift.getTill()){
                    createVisitCell(cell, visit);
                }
            }

        }
        return hours;
    }

    private void createVisitCell(LinearLayout cell, Visit visit) {
        TextView visitText = new TextView(this);
        visitText.setBackgroundResource(R.color.LIGHT_GRAY);
        String desc = visit.getDescription();
        if(desc.length() > 8){
            visitText.setText(desc.substring(0, 7));
        } else {
            visitText.setText(desc);
        }
        cell.addView(visitText);
    }

    private void addCell(String value, TableRow row) {
        TextView view = new TextView(this);
        view.setPadding(3, 3, 3 ,3);
        view.setText(value);
        view.setBackgroundResource(R.color.WHITE);

//        ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT,
//                ViewGroup.MarginLayoutParams.WRAP_CONTENT);
//        params.setMargins(1, 1, 1, 1);
//        row.addView(view, params);
        row.addView(view);
    }

    private void initHeaderTable() {
        TableRow dateRow = (TableRow)findViewById(R.id.workDayDateRow);
        TableRow shiftRow = (TableRow)findViewById(R.id.workDayShiftRow);
        for(int i = 0; i < 7; i++){
            TextView dateCell = (TextView)dateRow.getChildAt(i);
            dateCell.setText(format.format(workDays.get(i).getDate()));

            TextView shiftCell = (TextView)shiftRow.getChildAt(i);
            Shift shift = shifts.get(workDays.get(i).getShiftId());
            if(shift != null){
                shiftCell.setText(shift.getName());
            } else {
                shiftCell.setText("Day off");
            }
        }
    }

    public void newVisit(View view){
        Intent i = new Intent(this, NewVisitScr.class);
        i.putExtra("date", workDays.get(currentDay).getDate());
        startActivity(i);
    }
    
}

